<?php
/*******************************************************
*
* Page:    app_lib.class
* Author:  Matthew Sturges (matt@matthewsturges.com)
* Purpose: Base class for general library functions, like
*          date formatting and csv file creation, etc.
* Created: 06/29/05
* Version: 2.0
*
* Modified:
*    12/28/07 MF  Removed a reference to the old stdData class from the sql to csv function.
*    12/28/07 MF  Modified nice date function so that if strtotime fails the
*                 function will assume that it is being given an untix time stamp already.
*    01/26/06 TAL Moved in functions from wsList.php
*    11/17/06 TAL Add comments to database_dropdown
*    11/18/06 TAL Add a class option to database_dropdown
*
*******************************************************/

class app_lib  {

    function sql_to_csv($query, $filename, $write_header_row=true, $separator=',', 
                        $text_delimiter='"', $header_row_mask =''){
        //Check query not blank.
        if (!$query){
            die ("No query string sent");
        }

        //Check outfile path specified
        if (!$filename) {
            die ("No filename sent");
        }

        //Try query
        $result = app_data::mysql_query($query) or die ("sql2csv:Query failed.<br><br><b>QUERY:</b><BR>$query<br><br><bError</b><br>" . mysql_error());

        //Check query produced results.
        if (mysql_num_rows($result) == 0) {
            die ("Query returned no results.");
        }


        //if we want a header row, do it now
        if ($write_header_row){
            $count = mysql_num_fields($result);
            for ($i = 0; $i < $count; $i++){
                $h = mysql_field_name($result, $i);
                if ($header_row_mask){
                    $h = str_replace($header_row_mask, '', $h);
                }
                $header[] = $h;
            }//end for
            $output.= implode(",", $header) . "\n";
        }//end if

        //write out the individual rows
        while($row = mysql_fetch_row($result)){
            $output.= $text_delimiter . implode($text_delimiter . $separator . $text_delimiter, $row) . $text_delimiter . "\n";
        }//end while


        // stream the file to the user
        header("Content-type: application/octet-stream");
        //tell the browser what to do with this
        header("Content-Disposition: attachment; filename=" . $filename);
        header("Pragma: no-cache");
        header("Expires: 0");

        echo $output;
    }//end function sql_to_csv()



    function nice_date ($timestamp, $format) {
        if ($timestamp == '' || $timestamp == '0000-00-00 00:00:00' || $timestamp == '0') return '';
        if ($timestamp == 'now') {
            $timestamp = time();
        } else {
        	if (strtotime($timestamp) != false) {
        		$timestamp = strtotime($timestamp);
        	}
        }

        switch ($format) {
            case 'date' :
                $f = 'n/j/y';
                break;
            case 'datetime' :
                $f = 'n/j/y h:i:s A';
                break;
            case 'shortdatetime' :
                $f = 'n/j/y H:i:s';
                break;
            case 'time' :
                $f = 'h:i';
                break;
            case 'mysql_timestamp' :
                $f = 'Y-m-d H:i:s';
                break;
            case 'mysql_datestamp' :
                $f = 'Y-m-d';
                break;
        }
        return date($f,$timestamp);
    }

    function get_file($filename){
        //Open the file and read the text of it.
        $filename = $_SERVER['DOCUMENT_ROOT'] . '/' . $filename;
        //echo $filename;
        $handle = fopen($filename, "r");
        while (!feof($handle)) {
           $s.= fgets($handle, 4096);
        }
        fclose($handle);
        return $s;
    }

    function put_file ($filename, $content){
        $filename = $_SERVER['DOCUMENT_ROOT'] . '/' . $filename;
        //open the file
        //echo $filename;
        $handle = fopen($filename,'w');
        if (fwrite($handle, stripslashes($content)) === false){
            $result = false;
        } else {
            $result = true;
        }
        fclose($handle);
        return $result;
    }

    function create_file($filename, $content){
        $handle = fopen($filename, 'a');
        fwrite($handle, $content);
        fclose($handle);
    }

    function log_to_file ($filename, $line) {
        $filename = $_SERVER['DOCUMENT_ROOT'] . '/' . $filename;
        $line = wordwrap($line,80,"\n    ");
        $handle = fopen($filename, 'a');
        fwrite($handle, "[" . app_lib::nice_date('now', 'datetime') . "] ");
        if (!fwrite($handle, $line . "\n")){
            die ("I didn't log it...<br>filename is: " . $filename . " <br>line is: " . $line);
        }
        fclose($handle);
    }

    function safe_file_name($string){
        $string = str_replace(' ', '-', $string);
        $string = str_replace('/', '-', $string);
        $string = str_replace('\\', '-', $string);
        $string = str_replace('?', '-', $string);
        $string = strtolower($string);
        return $string;
    }

    function load_gif ($imgname){
       $im = @imagecreatefromgif ($imgname); /* Attempt to open */
       if (!$im) { /* See if it failed */
           $im = imagecreate (150, 30); /* Create a blank image */
           $bgc = imagecolorallocate ($im, 255, 255, 255);
           $tc = imagecolorallocate ($im, 0, 0, 0);
           imagefilledrectangle ($im, 0, 0, 150, 30, $bgc);
           /* Output an errmsg */
           imagestring ($im, 1, 5, 5, "Error loading $imgname", $tc);
       }
       return $im;
    }


    function textarea_to_html($text){
        $r = str_replace("\r\n", '<br>', $text);
        $r = str_replace("\n", '<br>', $r);
        return $r;
    }

    function date_in_future($days)  {
        // IN OBJECT: app_lib    LAST MOD: 2005-12-09 Jack
        // PURPOSE: calculate a date in the future from todays date
        // ENTER WITH: $days being the number of days into the future (or - for past)
        // RETURNS: date in future in YYYY/MM/DD format
        // USAGE: must first instance object like;       $Lib = new wsLib();
        // EXAMPLE: $new_date = $Lib->date_in_future($days);
        //////////////////////////////////////////////////////////////////////////////////////////
          // get today values
        $this_year = date("Y");
        $this_month = date("m");
        $this_day = date("d");
        $seconds = $days * 86400; // how many seconds in days
        $ts_current_day = mktime(0,0,0,$this_month,$this_day,$this_year); // timestamp for current date
        $ts_new_date = (int )$ts_current_day + (int )$seconds; // add seconds to get new timestamp date
        return date("Y/m/d",$ts_new_date);  // return YMD for new date
    }  // end function

    function dropdown_date($date="",$fld_name_prefix){
        // IN OBJECT: wsLib    LAST MOD: 2005-11-25 Jack
        // PURPOSE: displays three dropdown form fields, for day month year.
        // ENTER WITH: $date in YYYY-MM-DD format, or empty for current day, and
        //      fld_name_prefix. When posted by form, there will be three fields to process
        //      fld_name_prefix with _d _m and _y added. EG. mydate_d, mydate_m, and mydate_y
        // RETURNS: nothing
        // USAGE: must first instance object like;       $Lib = new wsLib();
        // EXAMPLE: $Lib->dropdown_date("2005-11-26","mydate"); 
        //          $Lib->dropdown_date("","mydate");
        //          $Lib->dropdown_date($obj->values['art_expiration_date'],"mydate");
        // Special Note:    If you will be saving the date to a single field you must combine them
        //                  before you call $obj->save().  Maybe like
        //                $obj->values['mydate'] = $_REQUEST['mydate_y'] ."-".$_REQUEST['mydate_m']
        //                  ."-".$_REQUEST['mydate_d'] ;
        /////////////////////////////////////////////////////////////////////////////////////////////
        
        //  split passed date, or if empth, use current date split
        if ($date) {
           list($my_year, $my_month, $my_day) = split('[/.-]', $date);
        } else {
            $my_year = date("Y");
            $my_month = date("m");
            $my_day = date("d");
        } // end if

        // set min and max years (- 5 years, and +9 years)
        if($my_year < date("Y")) {
            $min_year =$my_year;
        }else{
            $min_year = date("Y") - 6;
        } // endif($my_year <

        $max_year =  9 + (int) date("Y");

        echo "<font size='2'>Month";
        $fld_name =$fld_name_prefix . "_m";
        $this->pre_selected_dropdown("$fld_name",'1','12', $my_month, '1');
        echo "</font>";
        echo "<font size='2'>Day";
        $fld_name =$fld_name_prefix . "_d";
        $this->pre_selected_dropdown("$fld_name",'1','31', $my_day, '1');
        echo "</font>";
        echo "<font size='2'>Year";
        $fld_name =$fld_name_prefix . "_y";
        $this->pre_selected_dropdown("$fld_name","$min_year","$max_year", $my_year, '1');
        echo "</font>";
        
    } // end function dropdown_date()

   function pre_selected_dropdown($name,$start,$stop,$selected,$step) {
      if (empty($step)) {$step = '1';}          // set step to be 1 by default
      echo "   <select name='$name'>\n";
      for ($i=$start; $i<=$stop; $i=$i + $step) {
         if ($i == $selected) {
            echo "     <option selected>$i</option>\n";
         } else {
            echo "     <option>$i</option>\n";
         } // end if
      }; // end for
      echo "   </select>\n";
   } // end function

   // name is the name of the input
   // select is the SQL code to generate the selection list
   // id is the name of the primary key field
   // text is the query result field to display as text for the list
   // current_value is the selected id
   // null is a string to display for the null value, if empty there will be no null selection
   // dhtml is uses with any dhtml you need
   // one and only one id field you may exclude from the list
   function database_dropdown($name, $select, $id, $text, $current_value, $null, $class='', $dhtml='', $exclude='') {
        echo "<SELECT name='" . $name . "' id='" . $name . "' class='" . $class . "' $dhtml>\n";
        if ($null != '') {
            echo "<OPTION value=''>$null</OPTION>\n";
        }
        //echo $select;
        $result = mysql_query($select) or die("Query $select failed with " . mysql_error());
        while ($link = mysql_fetch_array($result, MYSQL_ASSOC)) {
            $selected = ($link[$id] == $current_value) ? ' SELECTED' : '';
            if (strlen (trim ($exclude)) > 0) {
               if (strcmp ($exclude, $link[$id])) {
                  echo "<OPTION value='" . $link[$id] . "'$selected>" . $link[$text] . "</OPTION>\n";
               } // end if not = exclude
            } // end if exclude
            else {
               echo "<OPTION value='" . $link[$id] . "'$selected>" . $link[$text] . "</OPTION>\n";
            } // end else, no exclude to chedk
        } // end while

        echo "</SELECT>\n";

    }//end function database_dropdown

    function array_dropdown($name, $id_array, $value_array, $selected_value, $null, $dhtml='') {
        $id_array = explode(',',$id_array);
        $value_array = explode(',',$value_array);
        echo "<SELECT name='$name' $dhtml >\n";
        if ($null != '') {
        echo "<OPTION value='null'>$null</option>\n";
        }
        foreach ($id_array as $i => $value) {
            $selected = ( $selected_value == $value ? ' SELECTED' : '');
            echo "<OPTION value='$value'$selected>" . $value_array[$i] . "</OPTION>\n";
        }
        echo "</SELECT>";
    }
    
    function state_dropdown($name, $current_value, $use_full_name, $null){
        echo "<SELECT name='$name'>\n";
        if ($null != '') {
            echo "<OPTION value=''>$null</OPTION>\n";
        }
        //echo $select;

        $states = array(
            'AL' => 'Alabama',
            'AK' => 'Alaska',
            'AZ' => 'Arizona',
            'AR' => 'Arkansas',
            'CA' => 'California',
            'CO' => 'Colorado',
            'CT' => 'Connecticut',
            'DE' => 'Delaware',
            'DC' => 'District of Columbia',
            'FL' => 'Florida',
            'GA' => 'Georgia',
            'HI' => 'Hawaii',
            'ID' => 'Idaho',
            'IL' => 'Illinois',
            'IN' => 'Indiana',
            'IA' => 'Iowa',
            'KS' => 'Kansas',
            'KY' => 'Kentucky',
            'LA' => 'Louisiana',
            'ME' => 'Maine',
            'MD' => 'Maryland',
            'MA' => 'Massachusetts',
            'MI' => 'Michigan',
            'MN' => 'Minnesota',
            'MS' => 'Mississippi',
            'MO' => 'Missouri',
            'MT' => 'Montana',
            'NE' => 'Nebraska',
            'NV' => 'Nevada',
            'NH' => 'New Hampshire',
            'NJ' => 'New Jersey',
            'NM' => 'New Mexico',
            'NY' => 'New York',
            'NC' => 'North Carolina',
            'ND' => 'North Dakota',
            'OH' => 'Ohio',
            'OK' => 'Oklahoma',
            'OR' => 'Oregon',
            'PA' => 'Pennsylvania',
            'RI' => 'Rhode Island',
            'SC' => 'South Carolina',
            'SD' => 'South Dakota',
            'TN' => 'Tennessee',
            'TX' => 'Texas',
            'UT' => 'Utah',
            'VT' => 'Vermont',
            'VA' => 'Virginia',
            'WA' => 'Washington',
            'WV' => 'West  Virginia',
            'WI' => 'Wisconsin',
            'WY' => 'Wyoming');


        foreach ($states as $abbr => $state_name) {
            $selected = ($abbr == $current_value) ? ' SELECTED' : '';
            echo "<OPTION value='" . $abbr . "'$selected>" . ($use_full_name ? $state_name : $abbr) . "</OPTION>\n";
        } // end while

        echo "</SELECT>\n";

    }//end function state_dropdown
}//end class app_lib
?>
